<script lang="ts">
import Vue, { CreateElement, VNode } from 'vue'
import { Component, Prop, Watch } from 'vue-property-decorator'
import _ from 'lodash'

export type TabConfig = Array<{ code: string; name: string }>

@Component({ name: 'com-tab' })
export default class ComTab extends Vue {
  @Prop({ type: String })
  value: string

  @Watch('value')
  onValueChange(val, oval) {
    if (val !== oval) {
      this.moveMask(val)
    }
  }

  mounted() {
    this.moveMask(this.value)
  }

  render(h: CreateElement): VNode {
    const slot = this.$slots.default
    const containers: Array<VNode> = []
    slot
      .filter(slt => {
        return !!slt.tag || !!_.trim(slt.text)
      })
      .forEach(slt => {
        const tagName = slt.data.attrs['data-tag']
        if (!tagName) {
          throw new Error('tab node must have a "data-tag" property')
        }
        containers.push(
          h(
            'div',
            {
              staticClass: 'tab-node',
              class: { active: tagName === this.value },
              ref: tagName,
              on: {
                click: this.onClick(slt),
              },
            },
            [slt],
          ),
        )
      })
    containers.push(h('div', { staticClass: 'tab-mask', ref: 'mask' }))
    return h('div', { staticClass: 'com-tab' }, containers)
  }

  onClick(child: VNode) {
    return function(e: MouseEvent) {
      const el = e.target as HTMLElement
      if (el.classList.contains('tab-node') && child.elm) {
        ;(child.elm as HTMLElement).click()
      }
    }
  }

  private moveMask(val) {
    const ref = this.$refs[val] as HTMLElement
    const mask = this.$refs.mask as HTMLElement
    if (ref) {
      mask.style.left = ref.offsetLeft + 'px'
      mask.style.width = ref.getBoundingClientRect().width + 'px'
    }
  }
}
</script>
<style lang="less">
@import url('../../styles/variable.less');

.com-tab {
  border-bottom: 1px solid @toolbar-border-color;
  position: relative;

  .tab-node {
    display: inline-block;
    padding: 10px;
    padding-bottom: 11px;
    margin-bottom: -1px;
    font-size: inherit;
    color: inherit;
    border-bottom: 2px solid transparent;
    cursor: pointer;
  }

  .tab-node.active {
    color: #000;
  }

  .tab-mask {
    display: inline-block;
    position: absolute;
    top: 0;
    bottom: 0;
    border-bottom: 2px solid #4a8bee;
    transition: left linear 0.1s;
    pointer-events: none;
  }

  a {
    text-decoration: none;
    color: inherit;
  }
}
</style>
